﻿using LineStickerDwonload.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using CatUtilsDll.Utils.Currency.WebUtils;
using CatUtils.Utils.Currency;
using CatUtils.Utils.SpecialUtils.Html;
using CatUtils.Utils.Currency.TextUtils;

namespace LineStickerDwonload.Linehelper
{
    internal class Scanner
    {
        public static void StartAsycn(String url)
        {
            LineStaticValue.Tip = ("扫描开始");
            WebHelper.HttpGetAsync(url, callBackDownStringCompleted, CallProgressCount);
        }

        private static void callBackDownStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            string FloderPath = LineTool.GetFloderPath(e.Result);

            if (HtmlHelper.GetFirstText(e.Result, "//span[@class='MdIcoPlay_b']") != "")
            {
                LineStaticValue.Tip = ("有声漫画");
                DownloadSound(e.Result, FloderPath);
            }
            else
            {
                LineStaticValue.Tip = ("普通漫画");
                DownloadImg(e.Result, FloderPath);
            }
        }

        private static void DownloadImg(string Result, string FloderPath)
        {
            StartDownload(LineTool.AnalysisImg(Result), new List<LineTool.DownloadInfo> { }, FloderPath);
        }

        /// <summary>
        /// 增强模式 支持下载声音
        /// </summary>
        /// <param name="result"></param>
        private static void DownloadSound(string result, string FloderPath)
        {
            List<LineTool.DownloadInfo> SoundList = new List<LineTool.DownloadInfo>();
            List<LineTool.DownloadInfo> ImgList = LineTool.AnalysisImg(result);
            foreach (string line in HtmlHelper.GetAttributesVlaueList(result, "style", "//ul[@class='mdCMN09Ul']//li/div/span"))
            {
                string ImgLink = TextHelper.RegexText(line, @"https://[\w\W].*?.(png|jpg)");
                string ImgID = LineTool.GetImgId(ImgLink);
            }
            StartDownload(ImgList, SoundList, FloderPath);
        }

        private static void StartDownload(List<LineTool.DownloadInfo> ImgList, List<LineTool.DownloadInfo> SoundList, string FloderPath)
        {
            LineStaticValue.LockProgress = true;
            LineStaticValue.MaxProgress = ImgList.Count + SoundList.Count;
            LineStaticValue.CurrentProgress = 0;
            DownLoad.InitStart(ImgList, SoundList, FloderPath);
        }

        private static void CallProgressCount(object sender, DownloadProgressChangedEventArgs e)
        {
            LineStaticValue.Tip = $"页面已解析:{ e.ProgressPercentage}%";
            Console.WriteLine(e.ProgressPercentage);
        }
    }
}